package com.example.eeuse.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.alibaba.fastjson2.JSONWriter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import org.redisson.client.codec.BaseCodec;
import org.redisson.client.codec.Codec;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class FastJsonCodec extends BaseCodec {

    private final Encoder encoder = in -> {
        String json = JSON.toJSONString(in, JSONWriter.Feature.WriteClassName.ordinal());
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
        out.writeBytes(bytes);
        return out;
    };

    private final Decoder<Object> decoder = (buf, state) -> {
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        return JSON.parseObject(bytes, Object.class);
    };

    @Override
    public Decoder<Object> getValueDecoder() {
        return decoder;
    }

    @Override
    public Encoder getValueEncoder() {
        return encoder;
    }
}

